/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.shoppingsystem.view.converters;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.jdesktop.beansbinding.Converter;

/**
 *
 * @author Usuario
 */
public class BytesImageIcon extends Converter<Object, Object> {

    @Override
    public Object convertForward(Object value) {
        return new ImageIcon((byte[]) value);
    }

    @Override
    public Object convertReverse(Object value) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            Image img = ((ImageIcon) value).getImage();
            if (img instanceof RenderedImage == false) {
                img = getBufferedImage(img, Transparency.TRANSLUCENT);
            }

            ImageIO.write((RenderedImage) img, "png", out);
        } catch (IOException ex) {
            Logger.getLogger(BytesImageIcon.class.getName()).log(Level.SEVERE, null, ex);
        }

        return out.toByteArray();
    }

    public static BufferedImage getBufferedImage(Image img, int transparency) {
        if (img instanceof BufferedImage) {
            return (BufferedImage) img;
        }

        GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
        BufferedImage bi = gc.createCompatibleImage(img.getWidth(null), img.getHeight(null), transparency);

        Graphics g = bi.createGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();
        return bi;
    }

}
